<template>
  <CustomerLayout>
    <div class="cart-container">
      <!-- 页面标题 -->
      <div class="page-header">
        <h2>我的购物车</h2>
        <div class="header-actions">
          <div class="cart-summary">
            <span class="total-items">共 {{ getTotalItems() }} 件商品</span>
            <span class="total-price">合计：¥{{ getTotalPrice().toFixed(2) }}</span>
          </div>
          <el-button 
            v-if="cartStores.length > 0"
            link 
            size="small" 
            @click="clearAllCart"
            class="clear-all-btn"
          >
            清空购物车
          </el-button>
        </div>
      </div>

      <!-- 购物车内容 -->
      <div class="cart-content">
        <!-- 购物车为空 -->
        <div v-if="cartStores.length === 0" class="empty-cart">
          <div class="empty-icon">
            <el-icon size="80"><ShoppingCart /></el-icon>
          </div>
          <h3>购物车空空如也</h3>
          <p>快去挑选喜欢的商品吧~</p>
          <el-button type="primary" @click="goToStoreList">去逛逛</el-button>
        </div>

        <!-- 购物车商品列表 -->
        <div v-else class="cart-stores">
          <div v-for="store in cartStores" :key="store.storeId" class="store-group">
            <!-- 店铺头部 -->
            <div class="store-header">
              <div class="store-info" @click="goToStore(store.storeId)">
                <el-icon class="store-icon"><Shop /></el-icon>
                <span class="store-name">{{ store.storeName }}</span>
                <span class="store-status" :class="getStoreStatusClass(store.storeStatus)">
                  {{ getStoreStatusText(store.storeStatus) }}
                </span>
              </div>
              <div class="store-actions">
                <el-button 
                  link 
                  size="small" 
                  @click="selectStoreItems(store.storeId)"
                  class="select-store-btn"
                >
                  选择本店
                </el-button>
                <el-button 
                  link 
                  size="small" 
                  @click="clearStoreCart(store.storeId)"
                  class="clear-store-btn"
                >
                  清空
                </el-button>
              </div>
            </div>

            <!-- 店铺商品列表 -->
            <div class="store-items">
              <div v-for="item in store.items" :key="item.id" class="cart-item">
                <div class="item-checkbox">
                  <el-checkbox 
                    v-model="item.selected" 
                    @change="updateItemSelection(item)"
                  />
                </div>
                
                <div class="item-image" @click="openFoodDetail(item)">
                  <el-image 
                    :src="item.foodImage" 
                    :alt="item.foodName"
                    fit="cover"
                    :lazy="true"
                  >
                    <template #error>
                      <div class="image-placeholder">
                        <el-icon><Picture /></el-icon>
                      </div>
                    </template>
                  </el-image>
                </div>

                <div class="item-content">
                  <div class="item-name" @click="openFoodDetail(item)">
                    {{ item.foodName }}
                  </div>
                  
                  <div v-if="item.attributes && item.attributes.length" class="item-specs">
                    <span v-for="(attr, index) in item.attributes" :key="index">
                      {{ attr.name }}: {{ attr.options.join(', ') }}
                      <span v-if="index < item.attributes.length - 1">; </span>
                    </span>
                  </div>
                  
                  <div class="item-meta">
                    <span class="item-price">¥{{ item.price.toFixed(2) }}</span>
                    <span class="item-total">小计: ¥{{ (item.price * item.quantity).toFixed(2) }}</span>
                  </div>
                </div>

                <div class="item-actions">
                  <div class="quantity-controls">
                    <el-button
                      type="danger"
                      icon="Minus"
                      circle
                      size="small"
                      @click="updateQuantity(item, -1)"
                      :disabled="item.quantity <= 1"
                    />
                    <span class="quantity">{{ item.quantity }}</span>
                    <el-button
                      type="primary"
                      icon="Plus"
                      circle
                      size="small"
                      @click="updateQuantity(item, 1)"
                    />
                  </div>
                  
                  <el-button 
                    link 
                    size="small" 
                    @click="removeItem(item)"
                    class="remove-btn"
                  >
                    删除
                  </el-button>
                </div>
              </div>
            </div>

            <!-- 店铺配送信息 -->
            <div class="store-delivery-info">
              <div class="delivery-details">
                <span class="delivery-fee">配送费: ¥{{ store.deliveryFee.toFixed(2) }}</span>
                <span class="min-order">起送价: ¥{{ store.minOrder.toFixed(2) }}</span>
                <span class="delivery-time">{{ store.deliveryTime }}分钟送达</span>
              </div>
              <div class="store-total">
                店铺小计: ¥{{ getStoreTotal(store).toFixed(2) }}
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 底部结算栏 -->
      <div v-if="cartStores.length > 0" class="checkout-bar">
        <div class="select-all">
          <el-checkbox 
            v-model="selectAll" 
            @change="toggleSelectAll"
            :indeterminate="isIndeterminate"
          >
            全选
          </el-checkbox>
        </div>
        
        <div class="price-summary">
          <div class="price-details">
            <span class="selected-count">已选 {{ getSelectedItems().length }} 件商品</span>
            <div class="price-breakdown">
              <span class="goods-price">商品金额: ¥{{ getSelectedGoodsPrice().toFixed(2) }}</span>
              <span class="delivery-fee">配送费: ¥{{ getSelectedDeliveryFee().toFixed(2) }}</span>
            </div>
          </div>
          <div class="total-price">
            合计: ¥{{ (getSelectedGoodsPrice() + getSelectedDeliveryFee()).toFixed(2) }}
          </div>
        </div>
        
        <div class="checkout-actions">
          <el-button 
            type="primary" 
            size="large"
            @click="goToCheckout"
            :disabled="getSelectedItems().length === 0 || !canCheckout"
          >
            去结算 ({{ getSelectedItems().length }})
          </el-button>
        </div>
      </div>
    </div>

    <!-- 商品详情弹窗 -->
    <el-dialog
      v-model="foodDetailVisible"
      :title="selectedFood?.foodName || '商品详情'"
      width="60%"
      @close="closeFoodDetail"
    >
      <div v-if="selectedFood" class="food-detail-popup">
        <div class="food-image">
          <el-image :src="selectedFood.foodImage" fit="cover" />
        </div>
        <div class="food-info">
          <h3>{{ selectedFood.foodName }}</h3>
          <p class="food-price">¥{{ selectedFood.price.toFixed(2) }}</p>
          <div v-if="selectedFood.attributes && selectedFood.attributes.length" class="food-specs">
            <h4>已选规格:</h4>
            <div v-for="(attr, index) in selectedFood.attributes" :key="index" class="spec-item">
              <span class="spec-name">{{ attr.name }}:</span>
              <span class="spec-value">{{ attr.options.join(', ') }}</span>
            </div>
          </div>
        </div>
      </div>
      <template #footer>
        <el-button @click="closeFoodDetail">关闭</el-button>
        <el-button type="primary" @click="goToStoreFromItem">查看店铺</el-button>
      </template>
    </el-dialog>
  </CustomerLayout>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onActivated } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { ShoppingCart, Shop, Picture, Plus, Minus } from '@element-plus/icons-vue';
import CustomerLayout from "@/components/customer/CustomerLayout.vue";
import { cartApi } from '@/api/customer';
import { CartItem } from '@/types/customer';

const router = useRouter();

// 购物车数据结构
interface CartStore {
  storeId: number;
  storeName: string;
  storeStatus: string;
  deliveryFee: number;
  minOrder: number;
  deliveryTime: number;
  items: (CartItem & { selected: boolean })[];
}

// 响应式数据
const loading = ref(false);
const cartStores = ref<CartStore[]>([]);
const selectAll = ref(false);
const foodDetailVisible = ref(false);
const selectedFood = ref<CartItem | null>(null);

// 计算属性
const isIndeterminate = computed(() => {
  const allItems = getAllItems();
  const selectedItems = allItems.filter(item => item.selected);
  return selectedItems.length > 0 && selectedItems.length < allItems.length;
});

const canCheckout = computed(() => {
  const selectedItems = getSelectedItems();
  if (selectedItems.length === 0) return false;
  
  // 检查选中的商品是否来自同一个商家
  const storeIds = [...new Set(selectedItems.map(item => item.storeId))];
  if (storeIds.length > 1) return false;
  
  // 检查是否达到起送价
  const storeId = storeIds[0];
  const store = cartStores.value.find(s => s.storeId === storeId);
  if (!store) return false;
  
  const storeTotal = selectedItems.reduce((sum, item) => sum + item.price * item.quantity, 0);
  return storeTotal >= store.minOrder;
});

// 获取购物车数据
const loadCartData = async () => {
  try {
    loading.value = true;
    console.log('开始加载购物车数据');
    
    const response = await cartApi.getCart();
    console.log('购物车API返回数据:', response);
    
    // 处理API返回数据，支持多种数据结构
    const cartData = response.data?.data || response.data || [];
    
    if (!Array.isArray(cartData)) {
      console.warn('购物车数据格式异常:', cartData);
      cartStores.value = [];
      return;
    }
    
    // 微信小程序版本直接返回按店铺分组的数据，Vue版本可能需要分组处理
    if (cartData.length > 0 && cartData[0].items) {
      // 如果数据已经按店铺分组（类似微信小程序格式）
      cartStores.value = cartData.map(store => ({
        storeId: store.id || store.storeId,
        storeName: store.storeName || store.name || '未知店铺',
        storeStatus: store.storeStatus || 'OPEN',
        deliveryFee: store.deliveryFee || 5,
        minOrder: store.minOrderAmount || store.minOrder || 20,
        deliveryTime: store.deliveryTime || 30,
        items: (store.items || []).map(item => ({
          ...item,
          storeId: store.id || store.storeId, // 确保每个商品都有storeId
          selected: false // 默认不选中
        }))
      }));
    } else {
      // 如果返回的是商品列表，需要按店铺分组
      const storeGroups = groupItemsByStore(cartData);
      cartStores.value = Object.keys(storeGroups).map(storeId => {
        const items = storeGroups[storeId];
        const firstItem = items[0];
        
        return {
          storeId: parseInt(storeId),
          storeName: firstItem.storeName || '未知店铺',
          storeStatus: firstItem.storeStatus || 'OPEN',
          deliveryFee: firstItem.deliveryFee || 5,
          minOrder: firstItem.minOrder || 20,
          deliveryTime: firstItem.deliveryTime || 30,
          items: items.map(item => ({ ...item, selected: false }))
        };
      });
    }
    
    console.log('处理后的购物车数据:', cartStores.value);
    updateSelectAllState();
    
  } catch (error) {
    console.error('获取购物车数据失败:', error);
    ElMessage.error('获取购物车数据失败');
    cartStores.value = [];
  } finally {
    loading.value = false;
  }
};

// 按店铺分组商品 - 处理单个商品列表的情况
const groupItemsByStore = (items: CartItem[]) => {
  if (!Array.isArray(items)) {
    console.warn('商品数据不是数组格式:', items);
    return {};
  }
  
  return items.reduce((groups, item) => {
    // 确保商品有storeId
    if (!item.storeId) {
      console.warn('商品缺少storeId:', item);
      return groups;
    }
    
    const storeId = item.storeId.toString();
    if (!groups[storeId]) {
      groups[storeId] = [];
    }
    groups[storeId].push(item);
    return groups;
  }, {} as Record<string, CartItem[]>);
};

// 获取所有商品
const getAllItems = () => {
  return cartStores.value.flatMap(store => store.items);
};

// 获取选中的商品
const getSelectedItems = () => {
  return getAllItems().filter(item => item.selected);
};

// 获取总商品数量
const getTotalItems = () => {
  return getAllItems().reduce((total, item) => total + item.quantity, 0);
};

// 获取总价格
const getTotalPrice = () => {
  return getAllItems().reduce((total, item) => total + item.price * item.quantity, 0);
};

// 获取选中商品价格
const getSelectedGoodsPrice = () => {
  return getSelectedItems().reduce((total, item) => total + item.price * item.quantity, 0);
};

// 获取选中商品的配送费
const getSelectedDeliveryFee = () => {
  const selectedItems = getSelectedItems();
  if (selectedItems.length === 0) return 0;
  
  const storeId = selectedItems[0].storeId;
  const store = cartStores.value.find(s => s.storeId === storeId);
  return store?.deliveryFee || 0;
};

// 获取店铺总价
const getStoreTotal = (store: CartStore) => {
  const selectedItems = store.items.filter(item => item.selected);
  const goodsTotal = selectedItems.reduce((sum, item) => sum + item.price * item.quantity, 0);
  return goodsTotal + (selectedItems.length > 0 ? store.deliveryFee : 0);
};

// 选择店铺所有商品
const selectStoreItems = (storeId: number) => {
  // 首先取消所有其他店铺的选择
  cartStores.value.forEach(store => {
    if (store.storeId !== storeId) {
      store.items.forEach(item => {
        item.selected = false;
      });
    } else {
      // 选择当前店铺的所有商品
      store.items.forEach(item => {
        item.selected = true;
      });
    }
  });
  
  updateSelectAllState();
  ElMessage.success('已选择该店铺的所有商品');
};

// 更新商品选择状态
const updateItemSelection = (item: CartItem & { selected: boolean }) => {
  // 如果选中了商品，需要检查是否与其他已选商品来自同一商家
  if (item.selected) {
    const selectedItems = getSelectedItems();
    const selectedStores = [...new Set(selectedItems.map(i => i.storeId))];
    
    // 如果已经有其他商家的商品被选中，取消当前选择
    if (selectedStores.length > 1) {
      // 取消其他商家的所有选择
      cartStores.value.forEach(store => {
        if (store.storeId !== item.storeId) {
          store.items.forEach(storeItem => {
            storeItem.selected = false;
          });
        }
      });
      ElMessage.warning('只能选择同一商家的商品进行结算');
    }
  }
  
  updateSelectAllState();
};

// 全选/取消全选
const toggleSelectAll = () => {
  if (selectAll.value) {
    // 如果是全选，需要检查是否有多个商家
    if (cartStores.value.length > 1) {
      ElMessage.warning('只能选择同一商家的商品进行结算，请点击店铺的"选择本店"按钮');
      selectAll.value = false;
      return;
    }
    
    // 只有一个商家时，全选该商家的商品
    const allItems = getAllItems();
    allItems.forEach(item => {
      item.selected = true;
    });
  } else {
    // 取消全选
    const allItems = getAllItems();
    allItems.forEach(item => {
      item.selected = false;
    });
  }
};

// 更新全选状态
const updateSelectAllState = () => {
  const allItems = getAllItems();
  const selectedItems = allItems.filter(item => item.selected);
  selectAll.value = allItems.length > 0 && selectedItems.length === allItems.length;
};

// 更新商品数量 - 参照微信小程序的逻辑
const updateQuantity = async (item: CartItem & { selected: boolean }, change: number) => {
  const newQuantity = item.quantity + change;
  
  console.log(`更新商品数量: ${item.foodName}, 当前: ${item.quantity}, 变化: ${change}, 新数量: ${newQuantity}`);
  
  // 如果新数量为0或负数，删除商品
  if (newQuantity <= 0) {
    await removeItem(item);
    return;
  }
  
  try {
    // 参照接口文档，调用更新购物车商品数量接口
    await cartApi.updateCartItem(item.id, { quantity: newQuantity });
    
    // 更新本地数据
    item.quantity = newQuantity;
    
    console.log('数量更新成功');
    ElMessage.success('数量已更新');
    
  } catch (error: any) {
    console.error('更新数量失败:', error);
    ElMessage.error(error.message || '更新数量失败');
    
    // 更新失败时重新加载购物车数据，确保数据准确性
    await loadCartData();
  }
};

// 删除商品 - 增强错误处理和数据同步
const removeItem = async (item: CartItem & { selected: boolean }) => {
  try {
    await ElMessageBox.confirm('确定要删除这个商品吗？', '确认删除', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });
    
    console.log('开始删除商品:', item.foodName, 'ID:', item.id);
    
    // 调用API删除商品
    await cartApi.removeFromCart(item.id);
    
    // 从本地数据中移除 - 参照微信小程序的处理逻辑
    cartStores.value.forEach(store => {
      const index = store.items.findIndex(i => i.id === item.id);
      if (index > -1) {
        store.items.splice(index, 1);
        console.log(`从店铺 ${store.storeName} 中删除商品`);
      }
    });
    
    // 移除没有商品的空店铺 - 参照微信小程序逻辑
    const originalLength = cartStores.value.length;
    cartStores.value = cartStores.value.filter(store => store.items.length > 0);
    
    if (cartStores.value.length < originalLength) {
      console.log('移除了空店铺');
    }
    
    updateSelectAllState();
    ElMessage.success('商品已删除');
    
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除商品失败:', error);
      ElMessage.error('删除商品失败');
      
      // 删除失败时重新加载数据
      await loadCartData();
    }
  }
};

// 清空店铺购物车 - 参照微信小程序的清空逻辑
const clearStoreCart = async (storeId: number) => {
  try {
    await ElMessageBox.confirm('确定要清空该店铺的购物车吗？', '确认清空', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });
    
    console.log('开始清空店铺购物车, 店铺ID:', storeId);
    
    // 调用API清空指定店铺购物车
    await cartApi.clearStoreCart(storeId);
    
    // 从本地数据中移除该店铺
    const originalLength = cartStores.value.length;
    cartStores.value = cartStores.value.filter(store => store.storeId !== storeId);
    
    if (cartStores.value.length < originalLength) {
      console.log('店铺购物车已从本地数据中移除');
    }
    
    updateSelectAllState();
    ElMessage.success('店铺购物车已清空');
    
  } catch (error) {
    if (error !== 'cancel') {
      console.error('清空购物车失败:', error);
      ElMessage.error('清空购物车失败');
      
      // 失败时重新加载数据确保一致性
      await loadCartData();
    }
  }
};

// 获取店铺状态样式
const getStoreStatusClass = (status: string) => {
  switch (status) {
    case 'OPEN': return 'status-open';
    case 'CLOSED': return 'status-closed';
    case 'BUSY': return 'status-busy';
    default: return '';
  }
};

// 获取店铺状态文本
const getStoreStatusText = (status: string) => {
  switch (status) {
    case 'OPEN': return '营业中';
    case 'CLOSED': return '休息中';
    case 'BUSY': return '繁忙';
    default: return '未知';
  }
};

// 打开商品详情
const openFoodDetail = (item: CartItem & { selected: boolean }) => {
  selectedFood.value = item;
  foodDetailVisible.value = true;
};

// 关闭商品详情
const closeFoodDetail = () => {
  selectedFood.value = null;
  foodDetailVisible.value = false;
};

// 导航功能
const goToStore = (storeId: number) => {
  router.push(`/customer/store/${storeId}`);
};

const goToStoreFromItem = () => {
  if (selectedFood.value) {
    router.push(`/customer/store/${selectedFood.value.storeId}`);
  }
};

const goToStoreList = () => {
  router.push('/customer/stores');
};

// 清空所有购物车 - 参照微信小程序的清空逻辑
const clearAllCart = async () => {
  try {
    await ElMessageBox.confirm('确定要清空所有购物车吗？', '确认清空', {
      confirmButtonText: '确定清空',
      cancelButtonText: '取消',
      type: 'warning',
      confirmButtonClass: 'el-button--danger'
    });
    
    console.log('开始清空所有购物车');
    
    // 调用API清空所有购物车
    await cartApi.clearCart();
    
    // 清空本地数据
    cartStores.value = [];
    updateSelectAllState();
    
    ElMessage.success('购物车已清空');
    
  } catch (error) {
    if (error !== 'cancel') {
      console.error('清空所有购物车失败:', error);
      ElMessage.error('清空购物车失败');
      
      // 失败时重新加载数据
      await loadCartData();
    }
  }
};
const goToCheckout = () => {
  const selectedItems = getSelectedItems();
  
  if (selectedItems.length === 0) {
    ElMessage.warning('请选择要结算的商品');
    return;
  }
  
  // 检查是否来自同一商家
  const storeIds = [...new Set(selectedItems.map(item => item.storeId))];
  if (storeIds.length > 1) {
    ElMessage.warning('只能选择同一商家的商品进行结算');
    return;
  }
  
  // 参照微信小程序，检查每个店铺是否达到起送价
  const storeId = storeIds[0];
  const store = cartStores.value.find(s => s.storeId === storeId);
  
  if (!store) {
    ElMessage.error('店铺信息异常');
    return;
  }
  
  // 计算选中商品的总价
  const storeTotal = selectedItems.reduce((sum, item) => sum + item.price * item.quantity, 0);
  
  if (storeTotal < store.minOrder) {
    ElMessage.warning(`${store.storeName}未达到起送价￥${store.minOrder.toFixed(2)}`);
    return;
  }
  
  console.log('准备跳转到结算页面, 选中商品:', selectedItems);
  
  // 保存结算数据到本地存储，供CheckoutView使用
  const checkoutData = {
    storeId: store.storeId,
    storeName: store.storeName,
    storeLogo: '', // 暂时设为空，后续可从store详情获取
    totalPrice: storeTotal,
    deliveryFee: store.deliveryFee,
    items: selectedItems
  };
  
  localStorage.setItem('checkoutData', JSON.stringify(checkoutData));
  
  // 跳转到结算页面，传递店铺ID参数
  router.push(`/customer/checkout?storeId=${store.storeId}`);
};

// 组件挂载时加载数据 - 参照微信小程序的onLoad和onShow
onMounted(() => {
  console.log('CartView组件已挂载，开始加载购物车数据');
  loadCartData();
});

// 监听路由变化，实现类似微信小程序onShow的效果
onActivated(() => {
  console.log('CartView页面激活，重新加载购物车数据');
  loadCartData();
});
</script>

<style scoped>
.cart-container {
  max-width: 95%;
  margin: 0 auto;
  padding: 20px;
  padding-bottom: 100px; /* 为底部结算栏留出空间 */
  min-width: 320px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #eee;
}

.page-header h2 {
  margin: 0;
  color: #333;
  font-size: 24px;
}

.header-actions {
  display: flex;
  align-items: center;
  gap: 15px;
}

.cart-summary {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  gap: 5px;
}

.clear-all-btn {
  color: #ff4757;
  font-size: 12px;
}

.total-items {
  color: #666;
  font-size: 14px;
}

.total-price {
  color: #ff6600;
  font-size: 18px;
  font-weight: bold;
}

/* 空购物车状态 */
.empty-cart {
  text-align: center;
  padding: 80px 20px;
  color: #999;
}

.empty-icon {
  margin-bottom: 20px;
  color: #ddd;
}

.empty-cart h3 {
  margin: 20px 0 10px;
  color: #666;
}

.empty-cart p {
  margin-bottom: 30px;
}

/* 购物车商品列表 */
.cart-stores {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.store-group {
  background: white;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.store-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 20px;
  background: #f8f9fa;
  border-bottom: 1px solid #eee;
}

.store-info {
  display: flex;
  align-items: center;
  cursor: pointer;
  gap: 8px;
}

.store-icon {
  color: #409EFF;
}

.store-name {
  font-weight: 600;
  color: #333;
}

.store-status {
  padding: 2px 8px;
  border-radius: 12px;
  font-size: 12px;
}

.status-open {
  background: #f0f9ff;
  color: #0ea5e9;
}

.status-closed {
  background: #fef2f2;
  color: #ef4444;
}

.status-busy {
  background: #fffbeb;
  color: #f59e0b;
}

.store-actions {
  display: flex;
  gap: 10px;
}

.select-store-btn {
  color: #409EFF;
}

.clear-store-btn {
  color: #ff4757;
}

.store-items {
  display: flex;
  flex-direction: column;
}

.cart-item {
  display: flex;
  align-items: center;
  padding: 15px 20px;
  border-bottom: 1px solid #f0f0f0;
  gap: 15px;
}

.cart-item:last-child {
  border-bottom: none;
}

.item-checkbox {
  flex-shrink: 0;
}

.item-image {
  width: 80px;
  height: 80px;
  border-radius: 8px;
  overflow: hidden;
  cursor: pointer;
  flex-shrink: 0;
}

.image-placeholder {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  background: #f5f5f5;
  color: #ccc;
}

.item-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.item-name {
  font-size: 16px;
  font-weight: 500;
  color: #333;
  cursor: pointer;
  line-height: 1.2;
}

.item-name:hover {
  color: #409EFF;
}

.item-specs {
  font-size: 12px;
  color: #999;
  line-height: 1.4;
}

.item-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.item-price {
  color: #ff6600;
  font-weight: 600;
}

.item-total {
  color: #666;
  font-size: 14px;
}

.item-actions {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 10px;
  flex-shrink: 0;
}

.quantity-controls {
  display: flex;
  align-items: center;
  gap: 10px;
}

.quantity {
  min-width: 30px;
  text-align: center;
  font-weight: 600;
}

.remove-btn {
  color: #ff4757;
  font-size: 12px;
}

.store-delivery-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 20px;
  background: #fafafa;
  font-size: 12px;
  color: #666;
}

.delivery-details {
  display: flex;
  gap: 15px;
}

.store-total {
  font-weight: 600;
  color: #ff6600;
}

/* 底部结算栏 */
.checkout-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  height: 80px;
  background: white;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1);
  display: flex;
  align-items: center;
  padding: 0 20px;
  z-index: 100;
}

.select-all {
  margin-right: 20px;
}

.price-summary {
  flex: 1;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.price-details {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.selected-count {
  color: #666;
  font-size: 14px;
}

.price-breakdown {
  display: flex;
  gap: 15px;
  font-size: 12px;
  color: #999;
}

.total-price {
  font-size: 20px;
  font-weight: bold;
  color: #ff6600;
}

.checkout-actions {
  margin-left: 20px;
}

/* 商品详情弹窗 */
.food-detail-popup {
  display: flex;
  gap: 20px;
}

.food-image {
  width: 200px;
  height: 200px;
  border-radius: 8px;
  overflow: hidden;
  flex-shrink: 0;
}

.food-info {
  flex: 1;
}

.food-info h3 {
  margin: 0 0 10px;
  font-size: 18px;
  color: #333;
}

.food-price {
  color: #ff6600;
  font-size: 20px;
  font-weight: bold;
  margin-bottom: 15px;
}

.food-specs h4 {
  margin: 0 0 10px;
  font-size: 14px;
  color: #666;
}

.spec-item {
  display: flex;
  margin-bottom: 5px;
  font-size: 14px;
}

.spec-name {
  color: #666;
  margin-right: 10px;
}

.spec-value {
  color: #333;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .cart-container {
    padding: 15px;
  }
  
  .page-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
  
  .cart-summary {
    align-items: flex-start;
  }
  
  .cart-item {
    padding: 12px 15px;
    gap: 10px;
  }
  
  .item-image {
    width: 60px;
    height: 60px;
  }
  
  .item-actions {
    flex-direction: row;
    gap: 5px;
  }
  
  .checkout-bar {
    flex-direction: column;
    height: auto;
    padding: 15px;
    gap: 10px;
  }
  
  .price-summary {
    flex-direction: column;
    align-items: flex-start;
    gap: 5px;
  }
  
  .food-detail-popup {
    flex-direction: column;
  }
  
  .food-image {
    width: 100%;
    height: 200px;
  }
}
</style>
